package org.example.route.controller.UserController;


import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.example.route.constant.UserConstant;
import org.example.route.model.dto.LoginDTO;
import org.example.route.model.dto.RegisterDTO;
import org.example.route.model.pojo.Result;
import org.example.route.model.pojo.User;
import org.example.route.model.vo.LoginVO;
import org.example.route.service.UserService;
import org.example.route.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
@Tag(name = "用户登录")
public class LoginController {

    @Autowired
    private UserService userService;

    //登录方法
    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result<LoginVO> login(@RequestBody LoginDTO loginDTO) {
        User user = userService.login(loginDTO);
        if(user == null) {
            return Result.error("用户名或密码错误");

        }

        if (user.getBanned().equals(UserConstant.BANNED)){
            return Result.error("用户被封禁");
        }

        Map claims = new HashMap<>();
        claims.put("userId",user.getId());
        claims.put("status",user.getStatus());

        //为微信用户生成令牌
        String token = JwtUtils.generateJwt(claims);

        LoginVO userLoginVO = new LoginVO(user.getId(), user.getStatus(), token, user.getName(), user.getAccount(), user.getAvatar());

        return Result.success(userLoginVO);

    }

    //注册方法
    @Operation(summary = "用户注册")
    @PostMapping("/register")

    public Result register(@RequestBody RegisterDTO registerDTO) {
        log.info("用户注册信息,{}",registerDTO);
        //TODO 写用户名去重逻辑
        userService.register(registerDTO);
        return Result.success();
    }


}
